<template>
	<div class="zd-billconfirm">
		<el-row style="height: 50px;line-height: 50px;">
			<el-col :span="6">
				<a class="back" @click="handleBack"><i class="iconfont icon-return"></i>返回列表</a>
			</el-col>
			<el-col :span="8">
				对账单：{{headBillNo}}
			</el-col>
			<el-col :span="8">
				<el-button type="primary" v-if="isAllChecked === false" @click="handleConfirm">确认</el-button>
			</el-col>
		</el-row>
		<div class="bill-info">
			<el-row>
				<el-col :span="8">
					结账年月：{{settleNo}}
				</el-col>
				<el-col :span="8">
					发布日期：{{publishTime}}
				</el-col>
				<el-col :span="8">
					状态：{{billState}}<a v-if="isAllChecked" style="padding-left:10px;color:blue;text-decoration:underline;" :href="origin+'/palmmall-web/download?billId='+currentRowList.uuid">ZD{{settleNo}}.pdf</a>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					商户：{{store}}
				</el-col>
				<el-col :span="8">
					合同编号：{{contract}}
				</el-col>
				<el-col :span="8">
					位置：{{position}}
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					合同期：{{contractRange}}
				</el-col>
				<el-col :span="8">
					合同类型：{{contractType}}
				</el-col>
				<el-col :span="8">
					收银方式：{{posType}}
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					应缴：{{payTotal}}
				</el-col>
				<el-col :span="8">
					已缴：{{payedTotal}}
				</el-col>
				<el-col :span="8">
					未缴：{{unpayedTotal}}
				</el-col>
			</el-row>					
		</div>
		<div class="bill-list" v-loading="loading">
			<el-table :data="tableData" height="250" class="main-content" style="width: 100%;" @selection-change="handleSelectionChange">
				<el-table-column type="selection" :selectable="selectableAction" width="55" align="center">
				</el-table-column>		
				<el-table-column width="60" min-width="60" type="index" label="序号" align="center">
				</el-table-column>
				<el-table-column prop="billNo" label="账单号" align="center">
				</el-table-column>
				<el-table-column prop="companyType" label="公司类型" align="center">
				</el-table-column>
				<el-table-column prop="subject" label="科目" align="center">
				</el-table-column>
				<el-table-column min-width="200" prop="dayTime" label="起止日期" align="center">
				</el-table-column>
				<el-table-column min-width="100" prop="lastDay" label="最后缴费日期" align="center">
				</el-table-column>
				<el-table-column prop="referencTotal" label="参考金额" align="center">
				</el-table-column>
				<el-table-column prop="payable" label="应缴" align="center">
				</el-table-column>
				<el-table-column prop="payedTotal" label="已缴" align="center">
				</el-table-column>
				<el-table-column prop="unpayedTotal" label="未缴" align="center">
				</el-table-column>									
				<el-table-column prop="state" label="状态" align="center">
				</el-table-column>
				<el-table-column v-if="false" prop="confirmed" label="是否已确认" align="center">
				</el-table-column>							
			</el-table>		
		</div>
	</div>
</template>

<script>
	export default {
		name: 'zd-billconfirm',
		data() {
			return {

				headBillNo:'', //对账单
				settleNo:'', // 结账年月
				publishTime:'', // 发布日期
				billState:'', // 账单状态
				store:'', // 商户
				contract:'', // 合同编号
				contractType: '', // 合同类型
				position:'', // 位置
				contractRange:'', // 合同期
				posType:'', // 收银方式
				payTotal:'', // 应缴
				payedTotal:'', // 已缴
				unpayedTotal:'', // 未缴

				tableData: [], // 当前展示的表格数组
				availableSelectedList:0, // 可选的列表长度

				loading: false, // 加载遮罩
				selectedBillLists:'', // 选中的账单列表
				multipleSelectionsAccId: [], // 多个对账单号的accId
				isSelecteAll:'', // 账单是否全选
				isAllChecked:'', // 账单是否为全确认账单

				origin: location.origin // 获取当前主机名及端口号
			}
		},
		computed:{
			currentRowList () {
				try{
					if(localStorage.getItem('currentBillNoOfBillList')){
						return JSON.parse(localStorage.getItem('currentBillNoOfBillList'))
					} else {
						throw new Error('localStorage中的currentBillNoOfBillList不存在,请返回列表，重新进入')
					}
				}catch(err){
					this.$message.error(`${err}`)
				}
			},
			companySubjects () {
				try{
					if(localStorage.getItem('loginResData')){
						return JSON.parse(localStorage.getItem('loginResData')).companies;
					} else {
						throw new Error('localStorage中的loginResData不存在,请重新登录')
					}
				}catch(err){
					this.$message.error(`${err}`)
				}
			}		
		},
		methods: {		
			handleBack(){
				// 删除localStorage中的currentBillNoOfBillList
				localStorage.removeItem('currentBillNoOfBillList');
				this.$router.push({
					path:'/Main/BillList'
				})
			},
			handleSelectionChange(val) {
				this.selectedBillLists = val;
			},
			selectableAction(row, index){
				// 当前行状态为已确认则禁止选择，否则能够选择
				if(row.confirmed === true){
					return false;
				} else {
					return true;
				}
			},
			handleConfirm() {
				// 至少选择一个账单
				if(!this.isSelecteAll){
					this.$message.error('对账单是选接口返回为空,无法进行账单确认操作');		
					return;					
				}else if(this.isSelecteAll != 'all'){
					this.$message.error(`对账单全选接口返回数据不合法,无法进行账单确认操作`);	
					return;			
				}else if(this.selectedBillLists.length != this.availableSelectedList) {
					this.$message.error('该账单仅供全选确认');		
					return;					
				}else if(this.selectedBillLists.length == 0) {
					this.$message.error('该账单均已确认，请勿重复操作');		
					return;					
				}else{
					this.$confirm('此操作将确认账单, 是否继续?', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then((e) => {
							// 消息提示，确认成功
							this.loading = true;
							this.$message.success('确认过程中，请耐心等待...');
							// 确认成功时的处理逻辑
							this.confirmedSuccess();
						}).catch((err) => {
							if(err == 'cancel') {
								this.$message.info('已取消确认');
							} else {
								this.$message.error(`${err}`);					
						}
					});
				}
			},
			initFetchSelectdState(){
				// 对账单是否为全选
				this.$axios.isSelecteAll()
				.then(res => {
					if(res.data.data){
						this.isSelecteAll = res.data.data
					}else{
						throw new Error('对账单全选接口返回为空,无法进行账单确认操作')
					}
				})
				.catch(err => {
					this.$message.error(`${err}`);
				})
			},
			initHeadData(){
				// 初始化页面头部数据
				this.headBillNo =this.currentRowList.billNo ? this.currentRowList.billNo : '---'; //对账单
				this.settleNo = this.currentRowList.billSettle ? this.currentRowList.billSettle.slice(0,4) + '年'+this.currentRowList.billSettle.slice(4) + '月' : '---'; // 结账年月
				this.publishTime = this.currentRowList.publishDate ? this.currentRowList.publishDate.split(' ')[0].split('-')[0]+'年'+this.currentRowList.publishDate.split(' ')[0].split('-')[1]+'月'+this.currentRowList.publishDate.split(' ')[0].split('-')[2]+'日' : '---'; // 发布日期		
				this.store = this.currentRowList.contract.name ? this.currentRowList.contract.name : '---'; // 商户
				this.contract = this.currentRowList.contract.code ? this.currentRowList.contract.code : '---'; // 合同编号
				this.contractType = this.currentRowList.contractType ? this.currentRowList.contractType : '---'; // 合同类型
				this.position = this.currentRowList.postion ? this.currentRowList.postion : '---'; // 位置
				this.contractRange = this.currentRowList.contractRange ? this.currentRowList.contractRange.split('～')[0].split(' ')[0] +'～'+ this.currentRowList.contractRange.split('～')[1].split(' ')[0]: '---'; // 合同期
				this.posType = this.currentRowList.posType ? this.currentRowList.posType : '---'; // 收银方式
				this.payTotal = this.currentRowList.payTotal || this.currentRowList.payTotal == 0 ? this.currentRowList.payTotal : '---'; // 应缴
				this.payedTotal = this.currentRowList.payedTotal || this.currentRowList.payedTotal == 0 ? this.currentRowList.payedTotal : '---'; // 已缴
				this.unpayedTotal = this.currentRowList.unpayedTotal || this.currentRowList.unpayedTotal == 0 ? this.currentRowList.unpayedTotal : '---'; // 未缴
				this.billState = this.currentRowList.billState ? this.currentRowList.billState : '---'; // 账单状态
				switch (this.billState) {
					case 'unpaid':
						this.billState = '已发布' 
						break;
					case 'confirmed':
						this.billState = '已确认'
						break;		
					case 'partialclosed':
						this.billState = '部分结款'
						break;
					case 'closed':
						this.billState = '已结款'
						break;
					default:
						this.billState = '状态未知'
						break;

				}
			},
			initFetchDetails(){
				const self = this;
				self.tableData = []
				self.availableSelectedList = 0
				self.loading = true;
				this.$axios.getDetailsFetch(self.currentRowList.uuid)
				.then(res => {
					if(res.data.data){
						// 返回数据与表格字段进行配对
						self.responseDataMatchTable(res)
					}
					self.loading = false;
				})
				.catch(err => {
					self.loading = false;
					this.$message.error(`${err}`);
				})
			},			
			responseDataMatchTable(res){
				const self = this;
				const resData = res.data.data;
				if(resData){
					// 获得总条目数
					self.total = resData.length;
					self.pageSize = resData.length;
					resData.forEach((backArr) => {
						// 初始化表格数据
						let listData={
							billNo: backArr.billNumber ? backArr.billNumber : '---',
							companyType: backArr.companyType ? backArr.companyType : '---',
							subject: backArr.subject.name ? backArr.subject.name : '---',
							dayTime: backArr.beginDate && backArr.endDate ? `${backArr.beginDate}~${backArr.endDate.slice(0,-8)}` : '---',
							lastDay: backArr.lastPayDate ? backArr.lastPayDate.split(' ')[0] : '---',
							payable: backArr.payTotal ? backArr.payTotal : '---',
							referencTotal: backArr.referencTotal || backArr.referencTotal == 0 ? backArr.referencTotal : '---',
							payTotal: backArr.payTotal ||  backArr.payTotal == 0 ? backArr.payTotal : '---',		
							payedTotal: backArr.payedTotal || backArr.payedTotal == 0 ? backArr.payedTotal : '---',
							unpayedTotal: backArr.unpayedTotal || backArr.unpayedTotal == 0 ? backArr.unpayedTotal : '---',
							state: backArr.state ? backArr.state : '---',
							accid: backArr.accId ? backArr.accId : '---', // 此为隐藏状态
							confirmed: backArr.confirmed ? backArr.confirmed : '---' // 账单是否可点击
						}
						// 账单状态
						switch (listData.state) {
							case 'unpaid':
								listData.state = '已发布'
								self.availableSelectedList++ // 获得可选的列表的个数		
								break;
							case 'confirmed':
								listData.state = '已确认'
								break;		
							case 'partialclosed':
								listData.state = '部分结款'
								self.availableSelectedList++
								break;
							case 'closed':
								listData.state = '已结款'
								self.availableSelectedList++
								break;								
						}						
						// 由科目获得公司类型
						this.companySubjects.forEach(val => {
							val.subjects.forEach(childVal => {
								if (listData.subject === childVal.name) {
									listData.companyType = val.companyType 
								}
							})
						})
						self.tableData.push(listData)
					})
				}

				// 获得该账单是否为全确认账单
				self.isAllChecked = self.tableData.every(val => {
					return val.confirmed === true
				})
			},
			confirmedSuccess(){
				const self = this;
				self.selectedBillLists.forEach(val => {
					self.multipleSelectionsAccId.push(val.accid)
				})
				this.$axios.getConfirmFetch(self.multipleSelectionsAccId)
				.then(res => {
					this.loading = false;
					this.$message.success('确认成功');
					this.initFetchDetails();		
				})
				.catch(err => {
					 this.$message.error(`${err}`);
				})				

			}			
		},
		mounted:function(){
			// 初始化头部数据
			this.initHeadData();
			// 初始化请求数据
			this.initFetchDetails();
			// 初始化请求全选或非全选状态
			this.initFetchSelectdState();
		}
	}
</script>

<style scoped lang="scss">
.zd-billconfirm {
  width: 100%;
  background-color: #ffffff;
  text-align: left;
  .back {
    cursor: pointer;
    height: 50px;
    display: inline-block;
	margin-left: 15px;
	color:black;
    .iconfont {
      display: inline-block;
      font-size: 30px;
      color: #666666;
      vertical-align: middle;
      margin-top: -3px;
    }
  }
}

.bill-info {
  margin: 10px 15px;
  padding: 5px;
  border: 1px solid #cccccc;
}

.bill-list {
  margin: 10px 15px;
}

.el-row {
  line-height: 30px;
}
.main-content {
  min-height: 425px;
}
</style>